package com.wnzt.baszh.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wnzt.baszh.util.common.GlobalStatic;

public class SessionTimeOutFilter implements Filter {
    protected FilterConfig filterConfig;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public Object getObject(String instance) {
        Object anInstance;
        try {
            @SuppressWarnings("rawtypes")
            Class aClass = Class.forName(instance);
            anInstance = aClass.newInstance();
            return anInstance;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setISsoValidate() {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();
        // 登陆url
        String loginUrl = httpRequest.getContextPath() + "/login";
        String url = httpRequest.getRequestURI();
        String path = url.substring(url.lastIndexOf("/"));

        // 超时处理，ajax请求超时设置超时状态，页面请求超时则返回提示并重定向
        if (path.indexOf("login") == -1 && path.indexOf("logon") == -1 && path.indexOf(".") == -1
                && session.getAttribute(GlobalStatic.USER_SESSION_OBJECT) == null) {

            // 判断是否为ajax请求
            if (httpRequest.getHeader("x-requested-with") != null
                    && httpRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                String isAddTab = httpRequest.getParameter("isAddTab");
                if (isAddTab != null && isAddTab.equals("true")) {
                    String str = "<script language='javascript'>alert('会话过期,请重新登录');"
                            + "window.top.location.href='" + loginUrl + "';</script>";
                    response.setContentType("text/html;charset=UTF-8");// 解决中文乱码
                    try {
                        PrintWriter writer = response.getWriter();
                        writer.write(str);
                        writer.flush();
                        writer.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    httpResponse.setContentType("text/html;charset=UTF-8");
                    httpResponse.addHeader("sessionstatus", "timeOut");
                    httpResponse.addHeader("loginPath", loginUrl);
                    httpResponse.setStatus(911);
                    try {
                        PrintWriter writer = response.getWriter();
                        writer.write("timeout");
                        writer.flush();
                        writer.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // chain.doFilter(request, httpResponse);// 不可少，否则请求会出错
                }
            } else {
                /*
                 * String str =
                 * "<script language='javascript'>alert('会话过期,请重新登录');" +
                 * "window.top.location.href='" + loginUrl + "';</script>";
                 * response.setContentType("text/html;charset=UTF-8");// 解决中文乱码
                 * try { PrintWriter writer = response.getWriter();
                 * writer.write(str); writer.flush(); writer.close(); } catch
                 * (Exception e) { e.printStackTrace(); }
                 */
                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }
}
